package my.jypark.seminar;

import java.io.DataInputStream;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: jypark
 * Date: 13. 10. 29
 * Time: 오후 2:01
 * To change this template use File | Settings | File Templates.
 */
public class LocalVariableTableAttribute extends Attribute {
    private short tableLen;

    private static class LocalVar {
        short start_pc;
        short length;
        String name;
        short descriptor_index;
        short index;
    }

    private LocalVar [] lvarTable;

    public LocalVariableTableAttribute(String name, DataInputStream ins) throws IOException {
        super(name, ins);
    }

    @Override
    protected void readData(DataInputStream ins, int len) throws IOException {
        tableLen = ins.readShort();
        lvarTable = new LocalVar[tableLen];

        for(int i=0; i<tableLen; i++) {
            LocalVar lv = new LocalVar();

            lv.start_pc = ins.readShort();
            lv.length = ins.readShort();
            lv.name = Loader.cmap.get(ins.readShort()).str;
            lv.descriptor_index = ins.readShort();
            lv.index = ins.readShort();

            lvarTable[i] = lv;
        }
    }

    @Override
    public int getLen() {
        return tableLen;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();

        sb.append("\n---- Local Variable Table ----\n");
        sb.append("table length : ").append(tableLen).append('\n');

        for (LocalVar lv:lvarTable) {
            sb.append("start PC : ").append(lv.start_pc).append('\n');
            sb.append("length : ").append(lv.length).append('\n');
            sb.append("name : ").append(lv.name).append('\n');
            sb.append("desc index : ").append(lv.descriptor_index).append('\n');
            sb.append("index : ").append(lv.index).append("\n\n");
        }

        return sb.toString();
    }
}
